import axios from 'axios'
import login from '../login/index'
// import Raven from '../Raven/index'
import {Toast} from 'mint-ui'

var dev = "dev";
var prod = "prod";
var readurl = "";
var Logs = "";
if(API_ENV === 'prod'){
  readurl = 'https://readingapi.qingclass.com/'
  // 正式日志服务url
  Logs = 'https://reading-service-log.cn-hangzhou.log.aliyuncs.com/logstores/reading-api/track?APIVersion=0.6.0';
}else {
  readurl = 'http://readingtest.qingclass.com/'
  //测试日志服务url
  Logs = 'http://test-service-log.cn-qingdao.log.aliyuncs.com/logstores/test-log/track?APIVersion=0.6.0';
}

var newreadapi = readurl + 'qing-user/api/'
var apiCommon = readurl + 'qing-user/api/v1.0.0/'
var api1 = readurl + 'qingread-ten-vip/api/v1.0.0/'
// 商品新借口
var api1_1 = readurl + 'qingread-ten-vip/api/v1.1.0/'
var api2 = readurl + 'qingread-ten-vip/api/v2.0.0/'
var readapi1 = readurl + 'api/v1.2/'
var readapi = readurl + 'api/v1.0/'
var readapi1_1 = readurl + 'api/v1.1/'
var readapi2 = readurl + 'api/v1.2/'
var qing_pay = readurl + 'qing-pay/api/v1.0/'
var qing_Punch = readurl + 'punch-tools/api/v1.0/'

// axios.defaults.headers.post['content-Type'] = 'appliction/json'
// axios.defaults.headers['Access-Control-Allow-Origin'] = '*'
axios.defaults.headers['Access-Control-Allow-Credentials'] = true
// axios.defaults.timeout = 10000

axios.interceptors.response.use((res) => {
  if (document.getElementById("topAlert")) {
    document.body.removeChild(document.getElementById("topAlert"));
  }
  if (res.data.qing_code === 800) {
    if (res.data.qing_data.params) {
      sessionStorage.setItem('BookShelfParams', JSON.stringify(res.data.qing_data.params))
    }
    // Toast({
    //   message: '正在登陆',
    //   iconClass: 'iconfont iicon-bangdingshibai',
    //   duration: 3000
    // })
    var querye = sessionStorage.getItem('querye')
    if (querye) {
      window.location.href = JSON.parse(querye).bigbayRedirectUrl
    } else {
      window.location.href = res.data.qing_data.location || window.location.href.split('#')[0] + '#/'
    }

    // window.location.href = res.data.qing_data.location || window.location.href.split('#')[0] + '#/'
    return new Promise(() => {
    });
  }
  if (res.data.qing_code === 401) {
    // Toast({
    //   message: '正在登陆',
    //   iconClass: 'iconfont iicon-bangdingshibai',
    //   duration: 3000
    // })
    window.localStorage.setItem('Ten_Vip_token', JSON.stringify({
      vip_user_id: -1,
      vip_token1: '-1',
      vip_token2: '-1',
      reading_vip_state: 0
    }))
    login.wx_auth_inspec()
    // return Promise.reject(res)
    // 返回pending状态的promise阻止 promise向下链式调用
    return new Promise(() => {
    });
  }
  if (res.data.qing_code === 719) {
    if (!res.data.success) {
      return Promise.reject(res)
    }
  }
  if (res.data.qing_code === 717) {
    window.location.href = window.location.href.split('#')[0] + '#/BuyVip'
    return new Promise(() => {
    });
  }
  if (res.data.qing_code !== 100 && res.data.qing_code !== 203 && res.data.qing_code !== 431 && res.data.qing_code !== 402 && res.data.qing_code !== 303 && res.data.qing_code !== 601 && res.data.qing_code !== 719) {
    window.localStorage.setItem('platform_user_info', JSON.stringify({user_id: -1, user_token: '-1'}))
    window.localStorage.setItem('Ten_Vip_token', JSON.stringify({
      vip_user_id: -1,
      vip_token1: '-1',
      vip_token2: '-1',
      reading_vip_state: 0
    }))
    // window.location.reload()
    return Toast({
      message: res.data.qing_text,
      iconClass: 'iconfont icon-bangdingshibai',
      duration: 3000
    })
  }
  if (!res.data.success) {
    return Promise.reject(res)
  }
  return res
}, (err) => {
  if (err && err.response) {
    // 跳转至错误页面
    window.location.href = window.location.href.split('#')[0] + '#/Error?errorStatus=' + err.response.status
    switch (err.response.status) {
      case 400:
        err.message = '请求错误'
        break
      case 401:
        err.message = '未授权，请登录'
        break

      case 403:
        err.message = '拒绝访问'
        break

      case 404:
        err.message = `请求地址出错: ${err.response.config.url}`
        break

      case 408:
        err.message = '请求超时'
        break

      case 500:
        err.message = '服务器内部错误'
        break

      case 501:
        err.message = '服务未实现'
        break

      case 502:
        err.message = '网关错误'
        break

      case 503:
        err.message = '服务不可用'
        break

      case 504:
        err.message = '网关超时'
        break

      case 505:
        err.message = 'HTTP版本不受支持'
        break

      default:
    }
  }
  return Promise.reject(err)
})
axios.interceptors.request.use((config) => {
  // config.headers.themeToken
  if (config.method === 'post') {
    // config.data = qs.stringify(config.data)
  }
  if (config.method === 'get') {
  }
  return config
}, error => {
  Toast({
    message: '网络异常',
    iconClass: 'iconfont icon-bangdingshibai',
    duration: 5000
  })
  return Promise.reject(error)
})

export function fetch(url, params) {
  params.platform_id = 5
  params.user_id = login.oauth_token.user_id
  params.user_token = login.oauth_token.user_token
  params.vip_user_id = login.Vip_token.vip_user_id
  params.vip_token1 = login.Vip_token.vip_token1
  params.vip_token2 = login.Vip_token.vip_token2
  // params = qs.stringify(params)
  return axios.post(url, params)
    .then(function (res) {
      return res.data
    }).catch(function (err) {
      return err
    })
}

export function putfetch(url, params) {
  params.platform_id = 5
  params.user_id = login.oauth_token.user_id
  params.user_token = login.oauth_token.user_token
  params.vip_user_id = login.Vip_token.vip_user_id
  params.vip_token1 = login.Vip_token.vip_token1
  params.vip_token2 = login.Vip_token.vip_token2
  return axios.put(url, params)
    .then(function (res) {
      return res.data
    }).catch(function (err) {
      return err
    })
}

export function getfetch(url, params) {
  params.params.platform_id = 5
  params.params.user_id = login.oauth_token.user_id
  params.params.user_token = login.oauth_token.user_token
  params.params.vip_user_id = login.Vip_token.vip_user_id
  params.params.vip_token1 = login.Vip_token.vip_token1
  params.params.vip_token2 = login.Vip_token.vip_token2
  return axios.get(url, params)
    .then(function (res) {
      return res.data
    }).catch(function (err) {
      return err
    })
}

export default {
  books_list: function (param) {
    return getfetch(api1 + 'book/list', {params: param})
  },
  books_shelf_list: function (param) {
    return getfetch(api1 + 'book_shelf/list', {params: param})
  },
  chapter_read: function (param) {
    return getfetch(api1 + 'chapter/read', {params: param})
  },
  exam_questions: function (param) {
    return getfetch(api1 + 'exam/questions', {params: param})
  },
  book_detail: function (param) {
    return getfetch(api1 + 'book/detail', {params: param})
  },
  chapter_detail: function (param) {
    return getfetch(api1 + 'chapter/read/chapter', {params: param})
  },
  achivement_chapter: function (param) {
    return getfetch(api1 + 'achivement/chapter', {params: param})
  },
  adver_list: function (param) {
    return getfetch(api1 + 'adver/list', {params: param})
  },
  goods_list: function (param) {
    return getfetch(api1_1 + 'goods/list', {params: param})
  },
  books_add: function (param) {
    return fetch(api1 + 'book_shelf/add', param)
  },
  exam: function (param) {
    return fetch(api1 + 'exam', param)
  },
  book_delete: function (param) {
    return fetch(api1 + 'book_shelf/delete', param)
  },
  //微信config
  wx_request_jsapi_sign: function (param) {
    // return getfetch(readapi1 + 'user_center/wechat/wx_request_jsapi_sign?' + new Date().getTime(), {params: param})
    return getfetch(newreadapi + 'wx_mp/js_api?' + new Date().getTime(), {params: param})
  },
  wx_auth_inspect: function (param) {
    return getfetch(newreadapi + 'wx_mp/wx_auth', {params: param})
    // return getfetch(readapi2 + 'user_center/wechat/wx_auth_inspect', {params: param})
  },
  share_link_info: function (param) {
    return getfetch(api1 + 'share_wechat/share_link_info', {params: param})
  },
  achivement_chapters: function (param) {
    return getfetch(api1 + 'achivement/chapter', {params: param})
  },
  achievement_card: function (param) {
    return getfetch(api1 + 'share_wechat/chapter/achievement_card', {params: param})
  },
  achievement_book_card: function (param) {
    return getfetch(api1 + 'share_wechat/book/achievement_card', {params: param})
  },
  order: function (param) {
    return getfetch(api1 + 'order', {params: param})
  },
  schedule: function (param) {
    return getfetch(api1 + 'schedule', {params: param})
  },
  inspect: function (param) {
    return getfetch(api1 + 'pay/inspect', {params: param})
  },
  location: function (param) {
    return getfetch(api1 + 'location', {params: param})
  },
  address_get: function (param) {
    return getfetch(api1 + 'address', {params: param})
  },
  share_books: function (param) {
    return getfetch(api1 + 'share_wechat/book/detail', {params: param})
  },
  rank: function (param) {
    return getfetch(api1 + 'rank', {params: param})
  },
  makeup_get: function (param) {
    return getfetch(api1 + 'order/makeup', {params: param})
  },
  address_post: function (param) {
    return fetch(api1 + 'address', param)
  },
  makeup_post: function (param) {
    return fetch(api1 + 'order/makeup/coupon', param)
  },
  makeup_check: function (param) {
    return getfetch(api1 + 'order/makeup/check', {params: param})
  },
  makeup_coupon: function (param) {
    return fetch(api1 + 'order/makeup/coupon', param)
  },
  share_done: function (param) {
    return fetch(api1 + 'share_wechat/share_done', param)
  },
  post_order: function (param) {
    return fetch(api1 + 'order', param)
  },
  country_code: function (param) {
    return getfetch(newreadapi + 'user_center/sms/country/code', {params: param})
  },
  send_code: function (param) {
    return getfetch(newreadapi + 'user_center/sms/send_code', {params: param})
  },
  // country_code_voice: function (param) {
  //   return putfetch(readapi + 'user_center/sms/send_code/voice', param)
  // },
  bind_phone: function (param) {
    return fetch(newreadapi + 'user_center/bind_phone', param)
  },
  wallet_info: function (param) {
    return getfetch(qing_pay + 'user_center/wallet/wallet_info', {params: param})
  },
  inspect_withdraw: function (param) {
    return getfetch(qing_pay + 'user_center/wallet/inspect_withdraw', {params: param})
  },
  confirm_withdraw: function (param) {
    return fetch(qing_pay + 'user_center/wallet/confirm_withdraw', param)
  },
  transaction_record: function (param) {
    return getfetch(qing_pay + 'user_center/wallet/transaction_record', {params: param})
  },
  cashback_record: function (param) {
    return getfetch(qing_pay + 'user_center/wallet/cashback_record', {params: param})
  },
  check_status: function (param) {
    return getfetch(qing_pay + 'wx_pay/check_status', {params: param})
  },
  chapter_books: function (param) {
    return getfetch(api1 + 'achivement/books', {params: param})
  },
  test_paper_question: function (param) {
    return fetch(readapi + 'exam/ability/test_paper_question', param)
  },
  exam_result: function (param) {
    return fetch(readapi + 'exam/ability/exam_result', param)
  },
  share: function (param) {
    return getfetch(readapi2 + 'market/share/share_link_info', {params: param})
  },
  vocabulary_info: function (param) {
    return getfetch(readapi2 + 'market/share/vocabulary_info', {params: param})
  },
  share_dones: function (param) {
    return getfetch(readapi + 'market/share/share_done', {params: param})
  },
  user_info: function (param) {
    return getfetch(newreadapi + 'user_center/user_info', {params: param})
    // return getfetch(readapi1_1 + 'user_center/user_info', {params: param})
  },
  user_settings: function (param) {
    // return getfetch(readapi2 + 'user_center/user_settings', {params: param})
    return getfetch(newreadapi + 'user_center/user_setting', {params: param})
  },
  user: function (param) {
    return fetch(api1 + 'user', param)
  },
  get_user: function (param) {
    return getfetch(api1 + 'user', {params: param})
  },
  get_card_order: function (param) {
    return getfetch(api1 + 'card/order', {params: param})
  },
  // oss上传授权
  get_sts: function (param) {
    return getfetch(apiCommon + 'common/oss_sts', param)
  },
  media_id_get_url: function (param) {
    return getfetch(apiCommon + 'common/media_id_get_url', {params: param})
  },
  // 奖学金列表
  scholarship: function (param) {
    return getfetch(api1 + 'scholarship', param)
  },
  // 初始化奖学金参数
  scholarship_init: function (param) {
    return getfetch(api1 + 'scholarship/init', param)
  },
  // 上传奖学金申请
  upload_scholarship: function (param) {
    return fetch(api1 + 'scholarship', param)
  },
  // 获取推荐书单及书籍
  recommend_book: function (param) {
    return getfetch(apiCommon + 'category/recommend_info', param)
  },
  // 获取新书推荐列表
  new_recommend_book: function (param) {
    return getfetch(apiCommon + 'category/recommend_book', param)
  },
  // 获取书籍分类
  category_list: function (param) {
    return getfetch(apiCommon + 'category/category_list', param)
  },
  // 根据相关种类查找该类的所有书籍
  category_book: function (param) {
    return getfetch(apiCommon + 'category/category_book', param)
  },
  logger: function () {
    var logger = new window.Tracker(Logs)
    return logger
  },
  get_coupon: function (param) {
    return getfetch(api1 + 'coupon', {params: param})
  },
  coupon_price: function (param) {
    return getfetch(api1 + 'coupon_price', {params: param})
  },
  post_coupon: function (param) {
    return fetch(api1 + 'coupon', param)
  },
  // 新书籍详情
  book_detail_new: function (param) {
    return getfetch(api2 + 'book/detail', {params: param})
  },
  // 新书籍详情
  free: function (param) {
    return getfetch(api1 + 'share_wechat/chapter/free', {params: param})
  },
  // 系统活动列表
  activity: function (param) {
    return getfetch(api1 + 'activity', {params: param})
  },
  //共读订单确认
  order_activity: function (param) {
    return getfetch(api1 + 'order/activity', {params: param})
  },
  //共读获取成就卡
  achivement_activity: function (param) {
    return getfetch(api1 + 'achivement/activity', {params: param})
  },
  //共读订单接口
  post_order_activity: function (param) {
    return fetch(api1 + 'order/activity', param)
  },
  user_activity: function (param) {
    return getfetch(api1 + 'user_activity', {params: param})
  },
  invite_code: function (param) {
    return getfetch(api1 + 'share_wechat/activity/invite_code', {params: param})
  },
  activation: function (param) {
    return fetch(api1 + 'user_activity/activation', param)
  },
  codes: function (param) {
    return getfetch(api1 + 'user_activity/codes', {params: param})
  },
  goods: function (param) {
    return getfetch(api1 + 'activity/goods', {params: param})
  },
  bigbay_coupon: function (param) {
    return getfetch(qing_pay + 'coupon/bigbay_coupon', {params: param})
  },
  getRemind: function (param) {
    return getfetch(api1 + 'user/remind', {params: param})
  },
  // 早起计划试听回调
  read_task_callback: function (param) {
    return getfetch(qing_Punch + 'task/read_task_callback', {params: param})
  },
  setRemind: function (param) {
    return fetch(api1 + 'user/remind', param)
  }
}
